//
//  MapViewController.m
//  A Learning Walk
//
//  Created by dllo on 16/6/13.
//  Copyright © 2016年 战斗民族. All rights reserved.
//
#import "MapViewController.h"

#import "SearchViewController.h"

#define APIkey  @"2fd17aa66b9bee1577524ff312ce562a"

@interface MapViewController ()<MAMapViewDelegate, AMapSearchDelegate, UITableViewDataSource, UITableViewDelegate>
{
    UIButton *_buttonHui;//定位按钮
    AMapSearchAPI *_search;//地址收索
    CLLocation *_currentLocation;//接收经纬度对象
    
}
@property(nonatomic, retain)MAMapView *mapView;//地图对象
@property(nonatomic, retain)UITextField *myText;//收索栏
@property(nonatomic, retain)UIButton *buttonG;//功能按钮
@property(nonatomic, retain)UIButton *buttonS;//收索按钮
@property(nonatomic, retain)UIView *viewG;//功能栏
@property(nonatomic, retain)UIView *viewL;//列表栏
@property(nonatomic, retain)UIVisualEffectView *effect;//磨玻璃
@property(nonatomic, retain)UITableView *myTable;//功能列表
@property(nonatomic, retain)NSMutableArray *myArray;//功能名单


@property(nonatomic, retain)NSMutableArray *annotations;

@property(nonatomic,strong)MAPointAnnotation *destinationPoint;

@property (nonatomic, strong) CLGeocoder *geoC;//地理编码

@property(nonatomic,strong)NSArray *pathPolylines;//路线规划数组


@end

@implementation MapViewController
-(void)dealloc{
    
    [_viewG release];
    [_myText release];
    [_mapView release];
    [_search release];
    [_currentLocation release];
    [_viewL release];
    [_effect release];
    [_myTable release];
    [_annotations release];
    [_myArray release];
    [_pathPolylines release];
    
#warning  移除通知中心
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"chuanzhi" object:nil];
    
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"地图";
    self.navigationController.navigationBar.hidden = YES;
    
    self.view.dk_backgroundColorPicker = DKColorPickerWithRGB(0xE0FFFF, 0x828282);
    
    self.myArray = [NSMutableArray arrayWithObjects:@"标准地图",@"卫星地图",@"夜间地图" ,nil];
    
#warning 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chuan:) name:@"chuanzhi" object:nil];
    
    self.pois = nil;//初始化不可变数组
    
    [self initMapview];
    [self initHuiButton];
    [self initText];
    [self initSearch];
    [self initPathBtn];
     // Do any additional setup after loading the view.
}
//创建收索
-(void)initSearch{
    //初始化
    _search = [[AMapSearchAPI alloc] init];
    //签协议
    _search.delegate = self;
}
//收索回调方法
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    
   //得到经纬度
    _currentLocation = [userLocation.location copy];
    
}

-(void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    if ([view.annotation isKindOfClass:[MAUserLocation class]]) {
        [self reGeoAction];
    }
}

//逆地理收索编码请求
-(void)reGeoAction{
    //如果获取经纬度
    if (_currentLocation) {
        //就获得一个泥地里收索编码的请求
        AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];
        //将其赋值经纬度
        request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
        [_search AMapReGoecodeSearch:request];
        
        [request release];
    }

}
//search回调方法
-(void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{
//    NSLog(@"%@",response);
//得到地址
    NSString *title = response.regeocode.addressComponent.city;
    if (title.length == 0) {
        title = response.regeocode.addressComponent.province;
    }
//点击小蓝色点,出现地址
    //大地址
    _mapView.userLocation.title = title;
    //小地址
    _mapView.userLocation.subtitle = response.regeocode.formattedAddress;
}

//创建收索栏 和功能列表
-(void)initText{
//收索框
    self.myText = [[UITextField alloc] initWithFrame:CGRectMake(60, 30, self.view.frame.size.width-120, 23)];
    self.myText.backgroundColor = [UIColor colorWithRed:165/255.0 green:178/255.0 blue:170/255.0 alpha:1];
    [self.view addSubview:self.myText];
    self.myText.font = [UIFont systemFontOfSize:15];
    self.myText.placeholder = @"输入搜索内容";
    self.myText.borderStyle = UITextBorderStyleRoundedRect;
    
    
//功能按钮
    self.buttonG = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonG.backgroundColor = [UIColor clearColor];
    self.buttonG.frame = CGRectMake(self.myText.frame.size.width+self.myText.frame.origin.x+15, 25, 30, 30);
    [self.buttonG addTarget:self action:@selector(buttonG:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonG setImage:[UIImage imageNamed:@"126"] forState:UIControlStateNormal];
    [self.view addSubview:self.buttonG];
//收索按钮
    self.buttonS = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonS.backgroundColor = [UIColor clearColor];
    self.buttonS.frame = CGRectMake(15, 25, 30, 30);
    [self.buttonS addTarget:self action:@selector(button1:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonS setImage:[UIImage imageNamed:@"130"] forState:UIControlStateNormal];
    [self.view addSubview:self.buttonS];
    
    [_myText release];
}

//显示地图
-(void)initMapview{
    //配置用户Key
    [AMapServices sharedServices].apiKey = APIkey;
//初始化对象
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 60,self.view.frame.size.width ,self.view.frame.size.height-60)];

    _mapView.delegate = self;
    
    [self.view addSubview:_mapView];
//打开定位
    _mapView.showsUserLocation = YES;
    
    [_mapView release];
}
//创建定位按钮
-(void)initHuiButton{
    _buttonHui = [UIButton buttonWithType:UIButtonTypeCustom];
    _buttonHui.frame = CGRectMake(20, _mapView.frame.size.height-95, 30, 30);
    _buttonHui.backgroundColor = [UIColor whiteColor];
    _buttonHui.autoresizingMask = UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin;
    _buttonHui.layer.cornerRadius = 5;
    [_buttonHui addTarget:self action:@selector(buttonHui:) forControlEvents:UIControlEventTouchUpInside];
    [_buttonHui setImage:[UIImage imageNamed:@"127"] forState:UIControlStateNormal];
    [_mapView addSubview:_buttonHui];
}
//定位按钮点击方法
-(void)buttonHui:(UIButton *)button{
    //定位模式 : 追中模式
    if (_mapView.userTrackingMode != MAUserTrackingModeFollow) {
        [_mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    }
}
//定位按钮点击状态改变
-(void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated{
    //没有定位模式
    if (mode == MAUserTrackingModeNone) {
        [_buttonHui setImage:[UIImage imageNamed:@"127"] forState:UIControlStateNormal];
    }else{
        //开启定位
        [_buttonHui setImage:[UIImage imageNamed:@"128"] forState:UIControlStateNormal];
    }
}

//功能按钮
-(void)buttonG:(UIButton *)button{
    
    NSLog(@"%d",button.selected);
    
    if (button.selected == NO) {
        //磨砂玻璃效果
        UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        self.effect = [[UIVisualEffectView alloc] initWithEffect:blur];
        self.effect.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 0);
        self.effect.alpha = 0.8;
        [self.view addSubview:self.effect];
        
        self.viewL = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 200)];
        self.viewL.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.viewL];
        //功能列表弹出外加动画
        [UIView animateWithDuration:0.5 animations:^{
            self.effect.frame = CGRectMake(0, 60, self.view.frame.size.width, self.view.frame.size.height-60);
            self.viewL.frame = CGRectMake( 0, self.view.frame.size.height-200, self.view.frame.size.width, 200);
        }];
        [self creatTable];
        
    }else{

        button.selected = !button.selected;
        return;
    }


    button.selected = !button.selected;
    [_effect release];
    [_viewL release];
}
-(void)creatTable{

    self.myTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.viewL.frame.size.width, self.viewL.frame.size.height) style:UITableViewStylePlain];
    self.myTable.backgroundColor = [UIColor whiteColor];
    [self.viewL addSubview:self.myTable];
    self.myTable.delegate = self;
    self.myTable.dataSource = self;
    [self.myTable registerClass:[MapTableViewCell class] forCellReuseIdentifier:@"reuse"];
    self.myTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.myTable release];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MapTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    cell.label.text = [self.myArray objectAtIndex:indexPath.row];
    cell.selectionStyle = NO;
    
    return cell;
}
//功能列表个数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.myArray.count;
}
//功能列表高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

//功能列表消失
-(void)viewLGet{
    //添加动画效果,改变功能栏,让其消失
    [UIView animateWithDuration:0.5f animations:^{
       self.effect.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 0);
       self.viewL.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 200);
    }];
    
}
//@property (nonatomic) MAMapType mapType; 地图类型
//MAMapTypeStandard = 0,  // 普通地图
//MAMapTypeSatellite,  // 卫星地图
//MAMapTypeStandardNight // 夜间视图

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
            [self viewLGet];
            _mapView.mapType = MAMapTypeStandard;
            NSLog(@"标准地图");
            break;
        case 1:
            [self viewLGet];
            _mapView.mapType = MAMapTypeSatellite;
            NSLog(@"卫星地图");
            break;
        case 2:
            [self viewLGet];
            _mapView.mapType = MAMapTypeStandardNight;
            NSLog(@"夜间地图");
            break;
        }

}


//周边搜索：适用于搜索某个位置附近的POI，可设置POI的类别，具体查询所在位置的餐饮类、住宅类POI，例如：查找天安门附近的厕所等等场景。请求参数类为 AMapPOIAroundSearchRequest，location是必设参数。

-(void)button1:(UIButton *)button{
    //当前位置为空或者搜索未初始化
    if (_currentLocation == nil || _search == nil) {
        
//        NSLog(@"%@",_currentLocation);
//        NSLog(@"%@",_search);
        NSLog(@"搜索失败");
        return;
    }
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
    //设置搜索的内容
    request.keywords = self.myText.text;
    //设置搜索结果的类型
    request.types = @"餐饮服务|生活服务|汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
    request.sortrule = 0;
    request.requireExtension = YES;
    
    //发起周边搜索
    [_search AMapPOIAroundSearch:request];
    
}

//实现POI搜索对应的回调函数 在搜索回调方法中得到搜索结果
-(void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    //没有搜到结果
    if (response.pois.count == 0) {
        return;
    }
    //搜到结果,先清空以前的
    if (response.pois.count > 0) {
        self.pois = response.pois;
        //清空标注
        [_mapView removeAnnotations:_annotations];
        [_annotations removeAllObjects];
    }
    
    [self.myTable reloadData];
    
//将搜索得到的结果通过属性传到二级页面tableView
    SearchViewController *seaVC = [[SearchViewController alloc] init];
    
    seaVC.pois1 = [NSMutableArray arrayWithArray:self.pois];
    
    [self presentViewController:seaVC animated:YES completion:^{
        
    }];
    
}

//完成传值,将搜索到的结果传回,显示在地图上
-(void)chuan:(NSNotification *)noti{
    //进行判断,如果有值,先清空
    if (self.destinationPoint != nil) {
        //清除以前的标注
        [self.mapView removeAnnotation:self.destinationPoint];
        self.destinationPoint = nil;
    }
    //接收传回来的值
    self.destinationPoint = noti.object;
    [_mapView addAnnotation:self.destinationPoint];
}


//长按按钮,添加大头针
- (void)mapView:(MAMapView *)mapView didLongPressedAtCoordinate:(CLLocationCoordinate2D)coordinate{
    
    [self.mapView removeAnnotations:self.annotations];
    [self.mapView removeAnnotation:self.destinationPoint];
    
    [self.annotations removeAllObjects];
    
    //在该点添加一个大头针(标注)
    
    self.destinationPoint = [[MAPointAnnotation alloc] init];
    
    self.destinationPoint.coordinate = coordinate;
    
    //反地理编码
    CLLocation *location = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    [self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //地标对象
        CLPlacemark *pl = [placemarks firstObject];
        
        //取详细地址
        NSString *name = pl.name;
        
        //获取城市
        NSString *city = pl.locality;
        
        self.destinationPoint.title = city;
        self.destinationPoint.subtitle = name;
        
        
    }];
    
    //将显示的中心切换到长按的地方
    // b) 设置缩放
    MACoordinateSpan span = MACoordinateSpanMake(0.01, 0.01);
    // c) 设置区域
    MACoordinateRegion region = MACoordinateRegionMake(coordinate, span);
    // d) 显示区域
    _mapView.region = region;
    //地图添加大头针
    [_mapView addAnnotation:self.destinationPoint];
    [self.annotations addObject:self.destinationPoint];
    
}

//点击地图,搜索键盘回收
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.myText resignFirstResponder];
}

//******************路线规划***********************

//长按手势方法
-(void)longPressAction:(UILongPressGestureRecognizer *)longPress{

    if (longPress.state == UIGestureRecognizerStateBegan) {
        /*!
         @brief 将指定view坐标系的坐标转换为经纬度 @param point 指定view坐标系的坐标 @param view 指定的view
         @return 经纬度
         */
        CLLocationCoordinate2D coordinate = [self.mapView convertPoint:[longPress locationInView:self.mapView] toCoordinateFromView:self.mapView];
        if (self.destinationPoint != nil) {
            //清除以前的标注
            [self.mapView removeAnnotation:self.destinationPoint];
            self.destinationPoint = nil;

            [_mapView removeOverlays:self.pathPolylines];
            self.pathPolylines = nil;

        }
        self.destinationPoint = [[MAPointAnnotation alloc] init];
        self.destinationPoint.coordinate = coordinate;

        [self.mapView addAnnotation:self.destinationPoint];

    }

}

//设置路线规划按钮
-(void)initPathBtn{
    UIButton *pathButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    pathButton.backgroundColor = [UIColor whiteColor];
    
    pathButton.frame = CGRectMake(20, _mapView.frame.size.height-155, 30, 30);
    pathButton.layer.masksToBounds = YES;
    pathButton.layer.cornerRadius = 5;
    [pathButton setImage:[[UIImage imageNamed:@"132"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [pathButton addTarget:self action:@selector(pathAction)
         forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:pathButton];

}


//路线按钮点击方法
-(void)pathAction{
    if (_destinationPoint == nil || _currentLocation == nil || _search == nil)
    {
        NSLog(@"路线规划失败");
        return; }
    //创建步行路径规划请求对象
    AMapWalkingRouteSearchRequest *request = [[AMapWalkingRouteSearchRequest alloc] init];

    request.origin = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];

    request.destination = [AMapGeoPoint locationWithLatitude:self.destinationPoint.coordinate.latitude longitude:self.destinationPoint.coordinate.longitude];

    //进行查询
    [_search AMapWalkingRouteSearch:request];
}


//实现路径搜索的回调函数 获取搜索结果
-(void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    if(response.route == nil){
      return;
    }

    //清空覆盖物
    if (response.count > 0) {
        //overrlays是覆盖物,polylines继承于overlay,可加载到地图上(还有标注)
        [self.mapView removeOverlays:self.pathPolylines];
        self.pathPolylines = nil;
    }
    //只显示第一条
    self.pathPolylines = [self polylinesForPath:response.route.paths[0]];
    [self.mapView addOverlays:self.pathPolylines];

    [self.mapView showAnnotations:@[self.destinationPoint,self.mapView.userLocation] animated:YES];
}

//路线解析方法
-(NSArray *)polylinesForPath:(AMapPath *)path{
    if (path == nil || path.steps.count == 0) {
        return nil;
    }
    NSMutableArray *polylines = [NSMutableArray array];
    //遍历每一个step
    [path.steps enumerateObjectsUsingBlock:^(AMapStep *step, NSUInteger idx, BOOL * _Nonnull stop) {
        NSUInteger count = 0;
        CLLocationCoordinate2D *coordinates = [self coordinatesForString:step.polyline coordinateCount:&count parseToken:@";"];

        //根据经纬度坐标生成多线段
        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
        [polylines addObject:polyline];
       free(coordinates),coordinates = NULL;
    }];

  return polylines;

}

//解析经纬度字符串

- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string
coordinateCount:(NSUInteger *)coordinateCount parseToken:(NSString *)token{
    if (string == nil){
        return NULL;
    }
    if (token == nil){
        token = @",";
    }
    NSString *str = @"";
    if (![token isEqualToString:@","]) {
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }else{
        str = [NSString stringWithString:string];
    }
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL) {
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D *)malloc(count * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i < count; i++) {
        coordinates[i].longitude = [[components objectAtIndex:2 * i]doubleValue];
        coordinates[i].latitude = [[components objectAtIndex:2 * i + 1]doubleValue];
    }
    return coordinates;

    }

//在获取并解析搜索结果后,添加polyline到地图
-(MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay{
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        MAPolylineRenderer *polylineRe = [[MAPolylineRenderer alloc] initWithOverlay:overlay];
        polylineRe.strokeColor = [UIColor blueColor];
        polylineRe.lineWidth = 4;

        return polylineRe;

    }

    return nil;
}

@end
